Telegram Group & Telegram Channel
✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_ci/1346
Create:
Last Update:

✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1346

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

Launched in 2013, Telegram allows users to broadcast messages to a following via “channels”, or create public and private groups that are simple for others to access. Users can also send and receive large data files, including text and zip files, directly via the app.The platform said it has more than 500m active users, and topped 1bn downloads in August, according to data from SensorTower.C C Sharp programming from in


Telegram C# (C Sharp) programming
FROM USA